<template>
  <div class="category-detail-container" :class="{ 'batch-mode': isBatchMode }">
    <!-- 页面头部 -->
    <div class="page-header">
      <van-icon name="arrow-left" class="back-button" @click="handleBack" />
      <span style="font-size: 16px; font-weight: bold"
        >{{ totalCount }}件单品</span
      >
      <div class="header-actions">
        <div
          v-if="!isBatchMode"
          @click="showFilterSidebar = true"
          class="filter-icon-container"
        >
          <van-badge :content="filterCount" :show-zero="false" color="#6c63ff">
            <img
              src="/src/assets/icons/filter.svg"
              alt="筛选"
              width="20"
              height="20"
            />
          </van-badge>
        </div>
        <div
          v-if="!isBatchMode"
          @click="toggleBatchMode"
          class="delete-icon-container"
        >
          <img
            src="/src/assets/icons/del.svg"
            alt="删除"
            width="20"
            height="20"
          />
        </div>
        <div v-else @click="toggleBatchMode" class="cancel-button">取消</div>
      </div>
    </div>

    <!-- 子分类标签 - 非批量模式下显示 -->
    <div v-if="!isBatchMode" class="subcategories-section">
      <div
        v-for="subCategory in subCategories"
        :key="subCategory.name"
        :class="[
          'subcategory-tag',
          { active: selectedSubCategory === subCategory.name },
        ]"
        @click="handleSubCategoryChange(subCategory.name)"
      >
        {{ subCategory.name }}
        <span v-if="subCategory.name !== '全部'" class="item-count">
          ({{ subCategory.count }})
        </span>
      </div>
    </div>

    <!-- 衣物列表网格 -->
    <div v-if="!isBatchMode">
      <ClothesImage :clothes="filteredClothes" />
    </div>
    <div v-else class="batch-mode-clothes-grid">
      <div
        v-for="clothes in filteredClothes"
        :key="clothes._id"
        class="batch-mode-clothes-item"
        @click="toggleClothesSelection(clothes._id)"
      >
        <div class="image-wrapper">
          <div
            class="selection-checkbox"
            :class="{ selected: selectedClothesIds.includes(clothes._id) }"
          >
            <van-icon
              v-if="selectedClothesIds.includes(clothes._id)"
              name="success"
              color="#fff"
              size="14"
            />
          </div>
          <img
            :src="clothes.imageUrls[0]"
            :alt="clothes.name"
            class="clothes-image"
          />
        </div>
      </div>
    </div>

    <!-- 底部提示 -->
    <!-- <div class="bottom-hint" v-if="filteredClothes.length > 0">
      没有更多数据了
    </div> -->

    <!-- 空状态 -->
    <div v-if="filteredClothes.length === 0 && !loading" class="empty-state">
      <!-- <div class="empty-icon">{{ categoryIcon }}</div> -->
      <img src="/src/assets/icons/empty.svg" alt="" style="width: 40%" />
      <p>这里还是空的</p>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-state">
      <van-loading type="spinner" />加载中...
    </div>

    <!-- 筛选侧边栏 -->
    <FilterSidebar
      v-model:show="showFilterSidebar"
      :categories="currentCategorySubcategories"
      @apply="handleFilterApply"
    />

    <!-- 批量删除底部操作栏 -->
    <div v-if="isBatchMode" class="batch-operation-bar">
      <div class="selected-count">
        已选
        <span style="color: darkorange">{{ selectedClothesIds.length }}</span>
        件
      </div>
      <div @click="deleteSelectedClothes">删除</div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useClothesStore } from "../store/clothes";
import { getCategoryIcon, clothesCategories } from "../utils/clothesCategory";
import ClothesImage from "../components/ClothesImage.vue";
import FilterSidebar from "../components/FilterSidebar.vue";
import { showToast, showConfirmDialog } from "vant";

const route = useRoute();
const router = useRouter();
const clothesStore = useClothesStore();

// 状态管理
const categoryName = ref("");
const loading = ref(false);
const selectedSubCategory = ref("全部");
const subCategories = ref([{ name: "全部", count: 0 }]);
const totalCount = ref(0);
const categoryIcon = ref("👕");
const currentCategory = ref(null);
const showFilterSidebar = ref(false);
const selectedFilters = ref({
  seasons: [],
  categories: [],
  colors: [],
});
const filterCount = ref(0);
// 批量删除相关状态
const isBatchMode = ref(false);
const selectedClothesIds = ref([]);

// 计算当前一级分类下的二级分类，用于传递给筛选组件
const currentCategorySubcategories = computed(() => {
  if (!currentCategory.value || !currentCategory.value.children) {
    return {};
  }

  const subcategoriesObj = {};
  currentCategory.value.children.forEach((child) => {
    // 计算每个子分类下的衣物数量
    const count = clothesStore.clothesList.filter((item) => {
      if (Array.isArray(item.type) && item.type.length > 0) {
        return item.type.some((t) => t.text === child.text);
      }
      return false;
    }).length;

    if (count > 0) {
      subcategoriesObj[child.text] = Array(count).fill(null); // 使用数组长度代表数量
    }
  });

  return subcategoriesObj;
});

// 根据选中的子分类和筛选条件筛选衣物
const filteredClothes = computed(() => {
  // 首先从store获取clothesList中属于当前一级分类的衣物
  let clothesList = clothesStore.clothesList.filter((item) => {
    // 处理type为数组的情况，确保能正确匹配一级分类名称
    if (Array.isArray(item.type) && item.type.length > 0) {
      // 查找与当前一级分类匹配的type元素
      return item.type.some((t) => t.text === categoryName.value);
    }
    // 同时兼容type为字符串的情况
    return item.type === categoryName.value;
  });

  // 根据子分类筛选
  if (selectedSubCategory.value !== "全部") {
    // 筛选属于选中子分类的衣物
    clothesList = clothesList.filter((item) => {
      if (Array.isArray(item.type) && item.type.length > 0) {
        // 查找type数组中是否包含匹配的子分类
        return item.type.some((t) => t.text === selectedSubCategory.value);
      }
      // 对于不支持子分类的数据结构，直接返回所有衣物
      return true;
    });
  }

  // 应用筛选条件
  // 季节筛选
  if (selectedFilters.value.seasons.length > 0) {
    clothesList = clothesList.filter((item) =>
      selectedFilters.value.seasons.includes(item.season)
    );
  }

  // 二级分类筛选（来自FilterSidebar）
  if (selectedFilters.value.categories.length > 0) {
    clothesList = clothesList.filter((item) => {
      if (Array.isArray(item.type) && item.type.length > 0) {
        return selectedFilters.value.categories.some((category) =>
          item.type.some((t) => t.text === category)
        );
      }
      return false;
    });
  }

  // 颜色筛选
  if (selectedFilters.value.colors.length > 0) {
    clothesList = clothesList.filter((item) =>
      selectedFilters.value.colors.includes(item.color)
    );
  }

  // 更新筛选计数
  filterCount.value = Object.values(selectedFilters.value).reduce(
    (acc, val) => acc + val.length,
    0
  );

  return clothesList;
});

// 返回上一页
const handleBack = () => {
  router.back();
};

// 切换子分类
const handleSubCategoryChange = (subCategory) => {
  selectedSubCategory.value = subCategory;
};

// 处理筛选条件应用
const handleFilterApply = (filters) => {
  selectedFilters.value = filters;
  // 当筛选条件变化时，重新加载子分类列表
  loadSubCategories();
  // 更新总数
  totalCount.value = filteredClothes.value.length;
};

// 根据分类加载衣物
const loadClothesByCategory = async () => {
  try {
    loading.value = true;

    // 从store获取所有衣物
    if (clothesStore.clothesList.length === 0) {
      await clothesStore.fetchClothesList();
    }

    // 获取当前一级分类信息
    currentCategory.value = clothesCategories.find(
      (cat) => cat.text === categoryName.value
    );

    // 设置分类图标
    categoryIcon.value = getCategoryIcon(categoryName.value);

    // 更新总数
    totalCount.value = filteredClothes.value.length;
  } catch (error) {
    console.error("加载衣物失败:", error);
  } finally {
    loading.value = false;
  }
};

// 加载子分类 - 只显示实际数据中存在的子分类
const loadSubCategories = async () => {
  try {
    // 从store获取clothesList
    if (clothesStore.clothesList.length === 0) {
      await clothesStore.fetchClothesList();
    }

    // 获取当前一级分类的子分类
    currentCategory.value = clothesCategories.find(
      (cat) => cat.text === categoryName.value
    );

    if (currentCategory.value && currentCategory.value.children) {
      // 添加'全部'选项，但只有在有数据时才添加
      const allOption = { name: "全部", count: filteredClothes.value.length };

      // 创建子分类列表并统计每个子分类下的衣物数量
      const subCategoryList = currentCategory.value.children.map((child) => {
        // 统计当前子分类下的衣物数量，考虑所有筛选条件
        const count = clothesStore.clothesList.filter((item) => {
          // 先检查是否属于当前一级分类
          const isInMainCategory =
            Array.isArray(item.type) && item.type.length > 0
              ? item.type.some((t) => t.text === categoryName.value)
              : item.type === categoryName.value;

          // 再检查是否属于当前子分类
          const isInSubCategory =
            Array.isArray(item.type) && item.type.length > 0
              ? item.type.some((t) => t.text === child.text)
              : false;

          // 应用季节筛选
          const matchesSeasonFilter =
            selectedFilters.value.seasons.length === 0 ||
            selectedFilters.value.seasons.includes(item.season);

          // 应用颜色筛选
          const matchesColorFilter =
            selectedFilters.value.colors.length === 0 ||
            selectedFilters.value.colors.includes(item.color);

          // 二级分类筛选（来自FilterSidebar）已经在filteredClothes中处理，
          // 但在计算子分类数量时需要排除当前正在计算的子分类以外的筛选
          let matchesCategoryFilter = true;
          if (selectedFilters.value.categories.length > 0) {
            // 当计算特定子分类的数量时，应包含该子分类，同时也包含用户选择的其他子分类
            matchesCategoryFilter =
              selectedFilters.value.categories.includes(child.text) ||
              (Array.isArray(item.type) &&
                item.type.length > 0 &&
                selectedFilters.value.categories.some((category) =>
                  item.type.some((t) => t.text === category)
                ));
          }

          return (
            isInMainCategory &&
            isInSubCategory &&
            matchesSeasonFilter &&
            matchesColorFilter &&
            matchesCategoryFilter
          );
        }).length;

        return {
          name: child.text,
          count: count,
        };
      });

      // 只保留实际存在数据的子分类（数量>0）
      const existingSubCategories = subCategoryList.filter(
        (subCategory) => subCategory.count > 0
      );

      // 更新子分类列表 - 当筛选后数据数量为0时，不显示"全部"选项
      if (filteredClothes.value.length === 0) {
        subCategories.value = existingSubCategories;
      } else {
        subCategories.value = [allOption, ...existingSubCategories];
      }
    } else {
      // 如果没有找到对应分类或该分类没有子分类，并且有数据时才显示"全部"选项
      if (filteredClothes.value.length === 0) {
        subCategories.value = [];
      } else {
        subCategories.value = [
          { name: "全部", count: filteredClothes.value.length },
        ];
      }
    }
  } catch (error) {
    console.error("加载子分类失败:", error);
  }
};

// 切换批量删除模式
const toggleBatchMode = () => {
  isBatchMode.value = !isBatchMode.value;
  // 退出批量模式时清空选择
  if (!isBatchMode.value) {
    selectedClothesIds.value = [];
  }
};

// 切换衣物选择状态
const toggleClothesSelection = (clothesId) => {
  const index = selectedClothesIds.value.indexOf(clothesId);
  if (index > -1) {
    selectedClothesIds.value.splice(index, 1);
  } else {
    selectedClothesIds.value.push(clothesId);
  }
};

// 删除选中的衣物
const deleteSelectedClothes = async () => {
  if (selectedClothesIds.value.length === 0) {
    showToast({
      message: "请先选择衣服",
    });
    return;
  }

  // 显示确认对话框
  showConfirmDialog({
    title: "删除衣服",
    message: `确定要删除选中的${selectedClothesIds.value.length}件衣物吗？\n此操作不可撤销。`,
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    confirmButtonColor: "#ff4d4f",
  })
    .then(async () => {
      try {
        loading.value = true;
        // 保存删除数量
        const deleteCount = selectedClothesIds.value.length;
        // 调用批量删除接口
        await clothesStore.deleteMultipleClothes(selectedClothesIds.value);
        // 重新加载数据
        await clothesStore.fetchClothesList();
        loadSubCategories();
        // 清空选择并退出批量模式
        selectedClothesIds.value = [];
        isBatchMode.value = false;
        // 更新总数
        totalCount.value = filteredClothes.value.length;
        showToast(`成功删除${deleteCount}件衣物`);
      } catch (error) {
        console.error("删除衣物失败:", error);
        showToast("删除失败，请重试");
      } finally {
        loading.value = false;
      }
    })
    .catch(() => {
      // 用户取消删除
    });
};

// 监听路由参数变化，重新加载数据
watch(
  () => route.query.name,
  (newName) => {
    if (newName) {
      categoryName.value = newName;
      loadClothesByCategory();
      loadSubCategories();
    }
  },
  { immediate: true }
);

// 页面挂载时加载数据
onMounted(() => {
  loadClothesByCategory();
  loadSubCategories();
});
</script>

<style scoped>
.category-detail-container {
  padding: 16px;
  margin: 0 auto;
  height: 100vh;
  position: relative;
  display: flex;
  flex-direction: column;

  /* background-color: #f5f5f5; */
}
.batch-mode {
  padding: 16px 16px 60px 16px;
}

/* 页面头部 */
.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-header h1 {
  font-size: 20px;
  font-weight: 600;
  margin: 0;
}

.back-button {
  font-size: 20px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.filter-icon-container,
.delete-icon-container {
  cursor: pointer;
}

.cancel-button {
  cursor: pointer;
}

/* 子分类标签 */
.subcategories-section {
  display: flex;
  overflow-x: auto;
  padding-bottom: 8px;
  -webkit-overflow-scrolling: touch;
  scrollbar-width: none;
}

.subcategories-section::-webkit-scrollbar {
  display: none;
}

.subcategory-tag {
  padding: 0px 16px;
  margin-right: 12px;
  border-radius: 20px;
  background-color: #ffffff;
  border: 1px solid #dac8c8;
  font-size: 14px;
  white-space: nowrap;
  transition: all 0.3s;
}

.subcategory-tag.active {
  background-color: #000000;
  color: white;
}

.item-count {
  opacity: 0.8;
}

/* 底部提示 */
.bottom-hint {
  text-align: center;
  color: #8c8c8c;
  font-size: 14px;
  padding: 20px 0;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 0;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
}

.empty-state p {
  color: #8c8c8c;
  margin: 8px 0;
}

/* 加载状态 */
.loading-state {
  text-align: center;
  padding: 60px 0;
  color: #8c8c8c;
}

/* 批量删除模式样式 */
.batch-mode-clothes-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(min(30%, 100px), 1fr));
  grid-auto-rows: 1fr;
  gap: 15px;
  width: 100%;
  box-sizing: border-box;
  align-items: start;
}

.batch-mode-clothes-item {
  position: relative;
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: 1px 1px 2px 1px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  -webkit-tap-highlight-color: transparent;
  flex-shrink: 0;
}

/* 触摸激活效果（针对移动端） */
.batch-mode-clothes-item:active {
  transform: scale(0.98);
  /* box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); */
}

.batch-mode-clothes-item:hover .clothes-image {
  transform: scale(1);
}

/* 触摸时图片缩放（针对移动端） */
.batch-mode-clothes-item:active .clothes-image {
  transform: scale(0.95);
}

.batch-mode-clothes-item .image-wrapper {
  position: relative;
  width: 100%;
  aspect-ratio: 1;
  overflow: hidden;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.clothes-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
  transition: transform 0.2s ease;
}

.selection-checkbox {
  position: absolute;
  top: 8px;
  left: 8px;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  border: 1.5px solid #e7e7e7;
  /* background-color: rgba(0, 0, 0, 0.5); */
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 10;
}

.selection-checkbox.selected {
  background-color: #6c63ff;
  border-color: #6c63ff;
}

/* 批量删除底部操作栏 */
.batch-operation-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60px;
  background-color: #fff;
  /* border-top: 1px solid #e8e8e8; */
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  /* box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1); */
}

.selected-count {
  color: #333;
}

.delete-selected-button {
  width: 100px;
  height: 40px;
  background-color: #ff4d4f;
  color: #fff;
  border-radius: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  cursor: pointer;
}

.delete-selected-button.disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .clothes-grid {
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
    gap: 12px;
  }

  .batch-mode-clothes-grid {
    grid-template-columns: repeat(auto-fill, minmax(min(32%, 100px), 1fr));
    gap: 10px;
  }
}

@media (max-width: 480px) {
  .batch-mode-clothes-grid {
    grid-template-columns: repeat(auto-fill, minmax(min(32%, 100px), 1fr));
    gap: 8px;
  }
}

@media (max-width: 360px) {
  .batch-mode-clothes-grid {
    grid-template-columns: repeat(auto-fill, minmax(min(32%, 100px), 1fr));
    gap: 6px;
  }
}
</style>
